#coding:utf8
'''
Created on 2018年8月26日

@author: liuna
'''
import time
import urllib
import urllib2
import cookielib
import urlparse
import json
import requests
import csv
import codecs


def read(page = 0):
    headers = {}
    headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0'
    headers['Accept'] = 'application/json, text/javascript, */*; q=0.01'
    headers['Accept-Language'] = 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2'
    headers['Accept-Encoding'] = 'gzip, deflate'
    headers['Referer'] = 'http://sc.122.gov.cn/views/vehxhhdpub.html'
    headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    headers['X-Requested-With'] = 'XMLHttpRequest'
    headers['Content-Length'] = '32'
    headers['Connection'] = 'keep-alive'
    
    url = 'http://sc.122.gov.cn/m/mvehxh/getDiscardList'
    body = {"glbm": "510100000400", "hpzl": "02", "page":page}
    
    response = requests.post(url, data = body, headers = headers)
    
    rst = json.loads(response.text)
    
    return rst['data']['content']
    


def readAll():
    count = 318
#     count = 1
    csvFile = open('dts.csv', 'w') 
    csvFile.write(codecs.BOM_UTF8)
    writer = csv.writer(csvFile)
    
    for page in range(count):
        lines = read(page)
        print page, len(lines)
        if page==0: writer.writerow(lines[0].keys())
        for line in lines:
            writer.writerow([fmt(e) for e in line.values()])
        time.sleep(1)
    csvFile.close()

def fmt(e):
    if type(e)==type(True): return str(e)
    if e==None: return 'None'
    return e.encode('utf8')
    
if __name__ == '__main__':
#     readAll()
    print time.localtime(18042400292630 / 1000)


